// /components/showinfobar.js
export function insertBarToolBeforeOrAfter(P_ParentElement, P_ChildElement, P_BarToolConfig, position) {
  if (!P_ParentElement || !P_ChildElement || !P_BarToolConfig) {
    console.error('Invalid arguments provided')
    return
  }

  // 找到子元素
  const child = P_ParentElement.querySelector(P_ChildElement)
  // 默认插入位置为before
  position = position || 'before'

  // 组装自定义按钮的html
  let customBtnHtml = showInfoBarTool(P_BarToolConfig)

  if (child) {
    // 判断插入位置
    if (position === 'before') {
      child.insertAdjacentHTML('beforebegin', customBtnHtml)
    } else if (position === 'after') {
      child.insertAdjacentHTML('afterend', customBtnHtml)
    } else {
      console.error('Invalid position specified, use "before" or "after"')
    }
    // 获取新插入的按钮元素
    const newButton = document.getElementById(P_BarToolConfig.id)
    if (newButton && P_BarToolConfig.click) {
      // 为按钮绑定 click 事件
      newButton.addEventListener('click', P_BarToolConfig.click)
    }
  } else {
    console.error('Child element not found')
  }
}

/**
 * @description 组装自定义按钮的html
 * @param P_BarToolConfig {Object} 自定义按钮配置
 * @returns {string} 自定义按钮的html
 */
function showInfoBarTool(P_BarToolConfig) {
  return `<div class="luckysheet-toolbar-button luckysheet-inline-block" 
              data-tips="${P_BarToolConfig.dataTips}" id="${P_BarToolConfig.id}" role="button" style="user-select: none;">
            <div class="luckysheet-toolbar-button-outer-box luckysheet-inline-block" 
              style="user-select: none;">
                <div class="luckysheet-toolbar-button-inner-box luckysheet-inline-block" 
                  style="user-select: none;">
                    <div class="luckysheet-icon luckysheet-inline-block " style="user-select: none;">
                      <div style="width: 100%; height: 100%; display: flex; align-items: center; justify-content: center;">
                        <svg aria-hidden="true" class="svg-icon" style="width: 1.8em;height: 1.8em;fill: currentColor;overflow: hidden;">
                          <use xlink:href="#icon-${P_BarToolConfig.icon}"></use>
                        </svg>
                      </div>
                    </div>
                </div>
            </div>
        </div>`
}
